﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Common.Tools
{
    public class MD5Helper
    {
        /// <summary>
        /// MD5算法
        /// </summary>
        /// <param name="dataStr"></param>
        /// <param name="codeType"></param>
        /// <returns></returns>
        public static string GetMD5(string dataStr, string codeType)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(System.Text.Encoding.GetEncoding(codeType).GetBytes(dataStr));
            var sb = new System.Text.StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="InStr"></param>
        /// <returns></returns>
        public static string GetEncryptCode(string InStr)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(InStr));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
            //MD5CryptoServiceProvider md5CSP = new MD5CryptoServiceProvider();
            //byte[] btEncrypt = Encoding.Unicode.GetBytes(InStr);
            ////加密数组
            //byte[] resultEncrypt = md5CSP.ComputeHash(btEncrypt);
            //string strEncrypt = Encoding.Unicode.GetString(resultEncrypt);
            ////作为密码方式加密
            //return FormsAuthentication.HashPasswordForStoringInConfigFile(strEncrypt, "MD5");
        }


        /// <summary> 
        /// MD5 Encrypt 
        /// </summary> 
        /// <returns>md5 Encrypt string</returns> 
        public static string MD5Encrypt(string inputString)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(Encoding.Default.GetBytes(inputString));
            return Encoding.Default.GetString(result);
        }

    }
}
